﻿using System;
using System.Collections.Generic;
using SeaBattle.Domain.Abstract;
using SeaBattle.Domain.Entities;
using System.Linq;
using SeaBattle.Domain.Abstract.Services;

namespace SeaBattle.Domain.Concrete
{
    public class FakeGameRepository: IGameRepository
    {
        /// <summary>
        /// fake game storage to avoid GC affects
        /// </summary>
        private static List<Game> games = new List<Game>();
        private IPlayerService playerService;
        private static bool Initialized = false;

        public FakeGameRepository(IPlayerService playerService)
        {
            this.playerService = playerService;
            if (!Initialized)
                InitializeGames();
        }

        /// <summary>
        /// generates next id value upon the fake storage
        /// </summary>
        /// <returns>generated id value</returns>
        private int GetNextId()
        {
            return games.Count + 1;
        }

        /// <summary>
        /// creates new game instance with creator player specified
        /// </summary>
        /// <param name="creator">creator player</param>
        /// <returns>created game instance</returns>
        public Game CreateNewGame(Player creator)
        {
            return new Game(GetNextId(), DateTime.Now, creator);
        }

        /// <summary>
        /// save current game instance to the storage
        /// </summary>
        /// <param name="game">game instance</param>
        /// <returns>successful saving flag</returns>
        public bool SaveGame(Game game)
        {
            if (!games.Contains(game))
            {
                games.Add(game);
            }
            return true;
        }


        /// <summary>
        /// Loads the game.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public Game GetGame(int id)
        {
            return games.FirstOrDefault(x => x.Id == id);
        }

        public IEnumerable<Game> GetAllGames()
        {
            return from a in games select a;
        }

        private void InitializeGames()
        {
            games.Add(new Game(1, DateTime.Now, playerService.GetPlayer("vasya")) { Preset = 100, Opened = true });
            games.Add(new Game(2, DateTime.Now, playerService.GetPlayer("vasya")) { Preset = 200, Opened = false });
            games.Add(new Game(3, DateTime.Now, playerService.GetPlayer("andrew")) { Preset = 300, Opened = true });
            games.Add(new Game(4, DateTime.Now, playerService.GetPlayer("vasya")) { Preset = 400, Opened = true });
            Initialized = true;
        }
    }
}
